<template>
  <div class="user-added">
    <!-- 新增用户 -->
    <div class="user-icon">
      <i class="iconfont">&#xe665;</i>
      <span>新增用户</span>
      <p class="added-p">请填写信息</p>
    </div>
    <!-- 基本信息 -->
    <div class="user-basic">
      <el-form
        :model="dynamicValidateForm"
        ref="dynamicValidateForm"
        label-width="100px"
        class="demo-dynamic"
        status-icon
        :rules="rules"
      >
        <div style="display: flex; justify-content: center;">
          <div>
            <el-form-item
              label="用户名："
              prop="username"
              autocomplete="off"
              :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]"
            >
              <el-input v-model="dynamicValidateForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码：" prop="password">
              <el-input v-model="dynamicValidateForm.password" type="password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPass">
              <el-input type="password" v-model="dynamicValidateForm.checkPass" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item
              prop="email"
              label="电子邮箱："
              :rules="[{ required: true, message: '请输入邮箱地址', trigger: 'blur' },{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }]"
            >
              <el-input v-model="dynamicValidateForm.email"></el-input>
            </el-form-item>
          </div>
          <div style="margin-left: 30px;">
            <el-form-item
              label="昵称："
              prop="nickName"
              autocomplete="off"
              :rules="[{ required: true, message: '请输入昵称', trigger: 'blur' }]"
            >
              <el-input v-model="dynamicValidateForm.nickName"></el-input>
            </el-form-item>
            <el-form-item
              label="备注："
              prop="note"
              autocomplete="off"
              :rules="[{ required: true, message: '请输入备注', trigger: 'blur' }]"
            >
              <el-input
                type="textarea"
                resize="vertical"
                :autosize="{ minRows: 2, maxRows: 4}"
                v-model="dynamicValidateForm.note"
              ></el-input>
            </el-form-item>
            <el-form-item label="头像：">
              <el-upload
                class="upload-demo"
                action
                :limit="1"
                list-type="picture"
                :auto-upload="false"
                :on-change="getFile"
              >
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过300kb</div>
              </el-upload>
            </el-form-item>
          </div>
        </div>
        <el-form-item style="display: flex; justify-content: center;margin-top: 30px;">
          <el-button
            type="primary"
            icon="el-icon-upload2"
            size="small"
            @click="submitForm('dynamicValidateForm')"
          >提交</el-button>
          <el-button icon="el-icon-back" size="small" @click="resetForm()">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  components: {},
  props: {},
  data() {
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号码不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error("请输入数字值"));
        } else {
          const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
          if (reg.test(value)) {
            callback();
          } else {
            return callback(new Error("请输入正确的手机号"));
          }
        }
      }, 1000);
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.dynamicValidateForm.checkPass !== "") {
          this.$refs.dynamicValidateForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.dynamicValidateForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      imageUrl: "", //上传图片
      dynamicValidateForm: {
        domains: [
          {
            value: ""
          }
        ],
        email: "", // 邮箱
        username: "", // 用户名
        password: "", // 密码
        checkPass: "", // 确认密码
        nickName: "", // 昵称
        note: "", // 备注
        phone: ""
      },
      rules: {
        phone: [{ trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }]
      }
    };
  },
  watch: {},
  computed: {},
  methods: {
    // 提交
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          var increased = {
            username: this.dynamicValidateForm.username,
            password: this.dynamicValidateForm.password,
            icon: this.imageUrl,
            email: this.dynamicValidateForm.email,
            nickName: this.dynamicValidateForm.nickName,
            note: this.dynamicValidateForm.note
          };
          this.$store
            .dispatch("User_register", increased)
            .then(data => {
              console.log("新增成功：" + JSON.stringify(data));
              this.$message({
                type: "success",
                message: "新增成功!"
              });
              this.$refs[formName].resetFields(); // 重置信息
              this.$router.replace({ name: "permission" }); // 成功后跳转到用户管理界面
            })
            .catch(error => {
              this.$notify.error({
                title: "新增失败",
                message: `${error}`
              });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 返回上一级
    resetForm() {
      this.$router.replace({ name: "permission" });
    },
    // 头像上传
    getFile(file, fileList) {
      console.log("file: " + JSON.stringify(file));
      this.getBase64(file.raw).then(res => {
        let images = "";
        images = res;
        this.imageUrl = images.replace(/^data:image\/\w+;base64,/, "");
      });
    },
    getBase64(file) {
      return new Promise(function(resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function() {
          imgResult = reader.result;
        };
        reader.onerror = function(error) {
          reject(error);
        };
        reader.onloadend = function() {
          resolve(imgResult);
        };
      });
    }
  },
  created() {},
  mounted() {}
};
</script>
<style scoped>
.user-icon {
  display: flex;
  height: 50px;
  text-align: left;
  align-items: center;
  border-bottom: 1px solid #eeeeee;
}
.user-icon span {
  font-size: 14px;
}
.added-p {
  color: #6379bb;
  font-size: 14px;
  margin-left: 15px;
}
.iconfont {
  margin-left: 15px;
  margin-right: 5px;
  font-size: 18px;
}
.user-basic {
  margin-top: 20px;
}

/* 头像上传 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  line-height: 78px;
  text-align: center;
}
.avatar {
  width: 78px;
  height: 78px;
  display: block;
}
</style>